package com.ninthgroup.util;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author ：1452863884@qq.com rcg
 * @date ：Created in 2022/10/29 17:52
 * @description：解决时间格式问题的工具类
 * @modified By：
 * @version:
 */
public class DateFormatUtil {


    /**
     * fetch data by show
     *
     * @param date
     * @return
     * @create by: 1452863884@qq.com rcg
     * @description:把date转为localdate
     * @create time: 2022/11/7 14:34
     */
    public static LocalDateTime dateToLocalDate(Date date) {

        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }


    /**
     * fetch data by show
     *
     * @param s
     * @return java.util.Date
     * @create by: 1452863884@qq.com rcg
     * @description:字符串转为Date
     * @create time: 2022/10/29 18:42
     */
    public static Date StringToDate(String s) {

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(s);

        } catch (Exception e) {
            throw new RuntimeException("字符串转化为日期失败");
        }
    }


    /**
     * fetch data by show
     *
     * @param date
     * @return java.lang.String
     * @create by: 1452863884@qq.com rcg
     * @description:把date转字符串 或者保留字符串
     * @create time: 2022/10/29 18:23
     */
    public static String DateToString(Date date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }


    /**
     * fetch data by show
     *
     * @param o
     * @return java.lang.Object
     * @create by: 1452863884@qq.com rcg
     * @description:通用的时间格式问题转化
     * @create time: 2022/10/29 17:54
     */
    public static Object checkObject(Object o) {
        //如果数据库中的类型为dateTime对应java中LocalDateTime
        //数据库中Date类型对应java中Date
        if (o instanceof LocalDateTime) {
            LocalDateTime date = (LocalDateTime) o;
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String format = date.format(dateTimeFormatter);
            return format;
        }
        return o;
    }


}

